package com.yykj.tencent.im.server.tdmq.config;

import com.yykj.tencent.im.server.tdmq.producer.ListMessageTemplate;
import com.yykj.tencent.im.server.tdmq.producer.MessageTemplate;
import com.yykj.tencent.im.server.tdmq.producer.ObjectMessageTemplate;
import com.yykj.tencent.im.server.tdmq.producer.StringMessageTemplate;
import org.apache.pulsar.client.api.AuthenticationFactory;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class TdmqAutoConfiguration {

    @Value("${tdmq.serviceUrl}")
    private String serviceUrl;
    @Value("${tdmq.token}")
    private String token;

    @Bean
    @ConditionalOnMissingBean
    public PulsarClient pulsarClient() throws PulsarClientException {
        return PulsarClient.builder()
                .serviceUrl(serviceUrl)
                //.listenerName(tdmqProperties.getListenerName())
                .authentication(AuthenticationFactory.token(token))
                .ioThreads(1)
                .listenerThreads(1)
                .enableTcpNoDelay(true)
                .keepAliveInterval(20, TimeUnit.SECONDS)
                .connectionTimeout(10, TimeUnit.SECONDS)
                .operationTimeout(20, TimeUnit.SECONDS)
                .startingBackoffInterval(100, TimeUnit.MILLISECONDS)
                .maxBackoffInterval(10, TimeUnit.SECONDS)
                .build();
    }

    /**
    @Bean("consumerMethodPostProcessor")
    public ConsumerMetadataPostProcessor consumerMethodPostProcessor() {
        return new ConsumerMetadataPostProcessor();
    }

    @Bean
    @DependsOn({"pulsarClient", "consumerMethodPostProcessor"})
    public ConsumerSubscribeFactory consumerSubscribeFactory(PulsarClient pulsarClient,
                                                             ConsumerMetadataMap consumerListenerMap,
                                                             TdmqProperties tdmqProperties) {

        return new ConsumerSubscribeFactory(pulsarClient, consumerListenerMap, tdmqProperties);
    }
  **/
    @Bean
    public <T> MessageTemplate<T> messageTemplate(PulsarClient pulsarClient) {
        return new MessageTemplate<>(pulsarClient);
    }


    @Bean
    public ListMessageTemplate listMessageTemplate(PulsarClient pulsarClient) {
        return new ListMessageTemplate(pulsarClient);
    }

    @Bean
    public ObjectMessageTemplate objectMessageTemplate(PulsarClient pulsarClient) {
        return new ObjectMessageTemplate(pulsarClient);
    }

    @Bean
    public StringMessageTemplate stringMessageTemplate(PulsarClient pulsarClient) {
        return new StringMessageTemplate(pulsarClient);
    }

}
